package github.sf.fw.tools.mybatis;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionManager;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;

/**
 * 原生的Mybatis使用
 *
 * @author zhoup
 */
public class PrimitiveMybatis {
    private final Configuration configuration = new Configuration();
    private SqlSessionManager sqlSessionManager;

    /**
     * addMapper方法一定要在initMybatisUtils方法之前
     *
     * @param mapperClass mapper
     */
    public void addMapper(Class<?> mapperClass) {
        configuration.addMapper(mapperClass);
    }

    /**
     * initMybatisUtils方法一定要在sqlSession方法之前
     *
     * @param dataSource 数据源
     */
    public void initMybatisUtils(DataSource dataSource) {
        initMybatisConfigAndEnv(dataSource);
        initSqlSessionFactory();
    }

    public SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionManager.openSession(autoCommit);
    }

    private void initMybatisConfigAndEnv(DataSource dataSource) {
        Environment environment = new Environment.Builder("simpleMybatisDataSource")
            .transactionFactory(new JdbcTransactionFactory())
            .dataSource(dataSource)
            .build();
        configuration.setEnvironment(environment);
        configuration.setLogImpl(StdOutImpl.class);
    }

    private void initSqlSessionFactory() {
        SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
        sqlSessionManager = SqlSessionManager.newInstance(sqlSessionFactory);
    }

    public void close() {
        if (sqlSessionManager != null) {
            sqlSessionManager.clearCache();
            sqlSessionManager.close();
        }
    }
}
